import router from './index'
import NProgress from 'nprogress'
import store from '../store';
import {removeToken} from '../utils/api/user.js';
import { Message } from 'element-ui'

const whiteList = ['/login'];

//钩子函数
router.beforeEach((to, from, next) => {
    NProgress.start();
    if (sessionStorage.getItem('access_token')) {
        if(to.path === '/login'){
            next('/');
            NProgress.done();
        }else{
            if(!store.getters.roleCode){
                store.dispatch('GetUserInfo').then( res => {
                    const roleCode = res.userRole.roleName;
                        store.dispatch('GenerateRoutes',roleCode).then(() =>{
                            router.addRoutes(store.getters.addRouters);
                            next({ ...to, replace: true });
                        })
                }).catch(err => {
                    removeToken().then(() =>{
                        Message.error(err || '验证失败 , 请重新登录');
                        next({ path: '/login' })
                    });
                })
            }else{
                next();
                NProgress.done();
            }
        }
    } else {
        if(whiteList.indexOf(to.path) != -1){
            next();
            NProgress.done();
        }else{
            next('/login');
            NProgress.done();
        }
    }
})